package com.example.demo.Controller;


import com.example.demo.Convert.AddRecieve;
import com.example.demo.Entity.*;
import com.example.demo.Repository.ShelfRepo;
import com.example.demo.Response;
import com.example.demo.Service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static java.time.LocalDateTime.now;

@RestController
@RequestMapping("/api/items")
@CrossOrigin(origins = "*")//允许所有同源访问，防止出现跨域问题
public class ItemController {

    private final ItemService itemService;
    private final UserService userService;
    private final WarehouseService warehouseService;
    private final ShelfService shelfService;
    private  final OperationLogService operationLogService;
    private final CurrentStorageService currentStorageService;


    @Autowired
    public ItemController(ItemService itemService,
                          UserService userService,
                          WarehouseService warehouseService,
                          ShelfService shelfService,
                          OperationLogService operationLogService,
                          CurrentStorageService currentStorageService) {
        this.itemService = itemService;
        this.userService =userService;
        this.warehouseService = warehouseService;
        this.shelfService = shelfService;
        this.operationLogService = operationLogService;
        this.currentStorageService = currentStorageService;
    }

    @PostMapping
    public Item createItem(@RequestBody Item item) {
        return itemService.createItem(item);
    }

    @GetMapping("/{id}")
    public Optional<Item> getItemById(@PathVariable Long id) {
        return itemService.getItemById(id);
    }


    @GetMapping
    public List<Item> getAllItems() {
        return itemService.getAllItems();
    }

    @PostMapping("/searchDistribution")
    public Map<String, Object> searchDistribution(@RequestBody Item item){
        System.out.println(item.getName());
        return itemService.searchDistribution(item);
    }

    @PostMapping("/intelligence")
    public Map<String,Object> intelligence(@RequestBody Item item){
        System.out.println(item);
        return itemService.intelligence(item);
    }



    @PutMapping("/{id}")
    public Map<String,Object> updateItem(@PathVariable Long id, @RequestBody Item item) {
        return itemService.updateItem(id, item);
    }

    @PutMapping
    public Map<String, Object> updateItemByName(@RequestParam String name, @RequestParam String newCategory, @RequestParam String newName) {
       return itemService.updateItemByName(name,newCategory,newName);
    }

    @DeleteMapping("/{id}")
    public Map<String, Object> deleteItem(@PathVariable Long id) {
        return itemService.deleteItem(id);
    }
    @PostMapping("/searchAll")
    public Map<String, Object> searchAllItems(){
        Map<String, Object> response = new HashMap<>();

       List<Item> t = itemService.getAllItems();
       if(t.isEmpty()){
           response.put("success",false);
           response.put("message","传输失败");
           return response;
       }
       else {
           response.put("success",true);
           response.put("message","传输成功");
           response.put("ItemList",t);////////可能出现数据对接问题，做个标记，后续出问题记得检查这里
           return response;
       }
    }
    @PostMapping("/search")
    public Map<String, Object> searchItemsByName(String name){
        Map<String, Object> response = new HashMap<>();

        Optional<Item> t = itemService.getItemByName(name);
        if(t.isEmpty()){
            response.put("success",false);
            response.put("message","传输失败");
            return response;
        }
        else {
            response.put("success",true);
            response.put("message","传输成功");
            response.put("Item",t.get());
            return response;
        }
    }

    @PostMapping("/updateDelete")//这里传参目测有问题，如果测试出现状况及的检查
    public Map<String, Object> updateDeleteItem(@RequestBody AddRecieve addRecieve) {
        Map<String, Object> response = new HashMap<>();
        //输入有三个
        String itemName = addRecieve.getItemName();
        String userName = addRecieve.getUserName();
        String weight = addRecieve.getItemWeight();
        double itemWeight = 0;
        System.out.println(addRecieve);

        try {
            itemWeight = Double.parseDouble(weight);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            response.put("success",false);
            response.put("message","输入的：itemWeight 不是数字");
            return response;
        }

        //判断物品是否存在
        Optional<Item> optionalItem = itemService.getItemByName(itemName);
        if(!optionalItem.isPresent()){
            response.put("success",false);
            response.put("message","物品："+ itemName+"不存在");
            return response;
        }

        Item item = optionalItem.get();
        System.out.println(item);

        User user = userService.findByUsername(userName).get();
        System.out.println(user);

        //判断当前物品总量
        double currentSum = currentStorageService.currentSum(item);
        if(currentSum < itemWeight){
            response.put("success",false);
            response.put("message","物品："+ itemName+"剩余量为："+currentSum+",小于请求值："+itemWeight);
            return response;
        }

        List<CurrentStorage> storages = currentStorageService.findByItem(item);
        Collections.sort(storages);

        for (int i = 0; i < storages.size(); i++) {
            //需要插入的数据有，log，需要修改，current，warehouse的current
            CurrentStorage storage = storages.get(i);
            double current = storage.getCurrentQuantity();
            if(current > itemWeight){
                itemService.updateByCurrentstorage(itemWeight,storage,user);
                break;
            }else{
                itemService.updateByCurrentstorage(current,storage,user);
                itemWeight -= current;
            }
        }

        response.put("success",true);
        response.put("message","出库成功");

        return response;

        }

    @PostMapping("/add")//这里传参目测有问题，如果测试出现状况及的检查
    public Map<String, Object> addItem(@RequestBody AddRecieve addRecieve) {
        System.out.println(addRecieve);

        String itemName = addRecieve.getItemName();
        String itemType = addRecieve.getItemType();
        String userName = addRecieve.getUserName();
        String weight = addRecieve.getItemWeight();
        String warehouseName = addRecieve.getWarehouseName();
        Map<String, Object> response = new HashMap<>();

        double itemWeight = 0;
        try {
            itemWeight = Double.parseDouble(weight);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            response.put("success",false);
            response.put("message","输入的：itemWeight 不是数字");
            return response;
        }


        Optional<Warehouse> warehouse = warehouseService.findByName(warehouseName);
        if(warehouse.isPresent()){
            Optional<Item> item = itemService.getItemByName(itemName);

            List<Shelf> shelfList = shelfService.findByWarehouse(warehouse.get());
            if (shelfList.isEmpty()){//该仓库没有货架
                response.put("success",false);
                response.put("message","添加失败：仓库："+warehouseName+"没有货架");
                return response;
            }
            Shelf shelf = shelfList.get(0);

            //找到最大剩余量的货架
            for (Shelf s : shelfList) {
                if(s.getCurrentStorage() > shelf.getCurrentStorage()){
                    shelf = s;
                }
            }

            if(item.isPresent()){//存在，需要插入log，current，warehouse的current

                //先插入log
                Optional<User> user = userService.findByUsername(userName);
                OperationLog log = new OperationLog();
                log.setWarehouse(warehouse.get());
                log.setItem(item.get());
                log.setUser(user.get());
                log.setIsRuku(true);
                log.setShelf(shelf);
                log.setQuantity(itemWeight);
                operationLogService.createOperationLog(log);

                //插入货架
                shelf.setCurrentStorage(shelf.getCurrentStorage()+itemWeight);
                shelfService.saveShelf(shelf);

                //再更改current
                CurrentStorage storage = new CurrentStorage();
                Optional<CurrentStorage> optional = currentStorageService.findCurrentStorageByWarehouseIdAndItemId(warehouse.get().getId(), item.get().getId());
                if(optional.isPresent()){
                    storage = optional.get();
                    storage.setCurrentQuantity(storage.getCurrentQuantity()+itemWeight);//已有需要减去，没有需要初始化
                }else{
                    storage.setItem(item.get());
                    storage.setWarehouse(warehouse.get());
                    storage.setCurrentQuantity(itemWeight);//已有需要减去，没有需要初始化
                }
                currentStorageService.saveCurrentStorage(storage);//这个方法很好，已有更新，没有则新建

                //更新warehouse的current
                warehouse.get().setCurrentStorage(warehouse.get().getCurrentStorage()+itemWeight);
                warehouseService.saveWarehouse(warehouse.get());

                response.put("success",true);
                response.put("message","物品："+item.get().getName()+"入库到仓库："+warehouseName+"的："+shelf.getId()+"货架上");


            }else {//物品不存在需要新建item,再插入log，current，warehouse的current
                //新建item
                Item newItem = new Item();
                newItem.setCategory(itemType);
                newItem.setName(itemName);
                newItem.setWeight(itemWeight);
                itemService.saveItem(newItem);


                //先插入log
                Optional<User> user = userService.findByUsername(userName);
                OperationLog log = new OperationLog();
                log.setItem(newItem);
                log.setUser(user.get());
                log.setIsRuku(true);
                log.setShelf(shelf);
                log.setQuantity(itemWeight);
                operationLogService.createOperationLog(log);

                //插入货架
                shelf.setCurrentStorage(shelf.getCurrentStorage()+itemWeight);
                shelfService.saveShelf(shelf);

                //再新建current
                CurrentStorage storage = new CurrentStorage();
                storage.setItem(newItem);
                storage.setWarehouse(warehouse.get());
                storage.setCurrentQuantity(itemWeight);//已有需要减去，没有需要初始化
                currentStorageService.saveCurrentStorage(storage);//这个方法很好，已有更新，没有则新建

                //更新warehouse的current
                warehouse.get().setCurrentStorage(warehouse.get().getCurrentStorage()+itemWeight);
                warehouseService.saveWarehouse(warehouse.get());

                response.put("success",true);
                response.put("message","物品："+item.get().getName()+"入库到仓库："+warehouseName+"的："+shelf.getId()+"货架上");
            }
        }else {
            response.put("success",false);
            response.put("message","添加失败：仓库："+warehouseName+"不存在");
        }
        return response;
    }

}

